﻿using System.Windows.Forms;
using AMatysiak.Methods;

namespace AMatysiak.Controls
{
    public class CurrencyBox : TextBox
    {
        public CurrencyBox()
            : base()
        {
            this.TextChanged += new System.EventHandler(CurrencyBox_TextChanged);
            this.TextAlign = HorizontalAlignment.Right;
            this.LostFocus += delegate { 
                formatText();
                interrupt = false; 
            };
        }

        private bool interrupt = false;

        private void CurrencyBox_TextChanged(object sender, System.EventArgs e)
        {
            if (interrupt)
                return;

            CurrencyBox box = (CurrencyBox)sender;
            try
            {
                interrupt = true;

                if (box.Text == "-" || box.Text == "+")
                    this.Value = 0;
                else
                    this.Value = box.Text.ToDouble();

                interrupt = false;
            }
            catch { }
        }

        private void formatText()
        {
            this.Text = value.ToString("C2");
        }

        private double value;
        public double Value
        {
            get { return value; }
            set
            {
                this.value = value;

                if (!this.Focused)
                    formatText();
            }
        }
    }
}
